﻿using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UMLSynthesizer.LangAnalyzer.Statements;

namespace UMLSynthesizer.CSharpAnalyzer.Statements
{
    class CSharpTryStatement : CSharpStatementBase, ITryStatement
    {
        #region Fields

        IEnumerable<IStatementBase> _containedStatements;

        #endregion

        #region Constructor

        public CSharpTryStatement(TryStatementSyntax statementNode, IStatementBase parentStatement)
            : base(statementNode, parentStatement, null, StatementKinds.Try) { }

        #endregion

        #region Properties

        public IEnumerable<IStatementBase> ContainedStatements
        {
            get
            {
                if (_containedStatements == null)
                {
                    var blockList = new List<IStatementBase>();
                    blockList.Add(new CSharpBlockStatement((statementNode as TryStatementSyntax).Block, this));
                    foreach (var catchBlock in (statementNode as TryStatementSyntax).Catches)
                        blockList.Add(new CSharpCatchClause(catchBlock, this));
                    if ((statementNode as TryStatementSyntax).Finally != null)
                        blockList.Add(new CSharpFinallyClause((statementNode as TryStatementSyntax).Finally, this));

                    _containedStatements = blockList;
                }
                return _containedStatements;
            }
        }
        public IEnumerable<ICatchClause> Catches
        {
            get
            {
                return from statement in ContainedStatements
                       where statement.Kind == StatementKinds.Catch
                       select statement as ICatchClause;
            }
        }
        public IFinallyClause Finally
        {
            get
            {
                return (from statement in ContainedStatements
                        where statement.Kind == StatementKinds.Finally
                        select statement as IFinallyClause).FirstOrDefault();
            }
        }

        #endregion
    }
}
